<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="allCheck" /> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr
          is="GoodList"
          v-for="(obj, index) in goodList"
          :key="index"
          :obj="obj"
          :index="index"
        ></tr>
      </tbody>
      <tfoot>
        <tr is="Total"></tr>
      </tfoot>
    </table>
    <div>
      <span>请输入商品名称：</span>
      <input type="text" v-model="goods.name" />
    </div>
    <div>
      <span>请输入商品价格：</span>
      <input type="text" v-model.number="goods.price" />
    </div>
    <div>
      <span>请输入商品数量：</span>
      <input type="text" v-model.number="goods.num" />
    </div>
    <button @click="addFn">添加</button>
  </div>
</template>

<script>
import GoodList from '@/components/GoodList.vue'
import Total from '@/components/Total.vue'
import { mapState } from 'vuex'
export default {
  components: {
    GoodList,
    Total,
  },
  computed: {
    ...mapState(['goodList']),
    allCheck: {
      set(val) {
        this.goodList.forEach((item) => (item.checked = val))
      },
      get() {
        return this.goodList.length
          ? this.goodList.every((item) => item.checked)
          : false
      },
    },
  },
  data() {
    return {
      goods: {
        name: '',
        price: '',
        num: '',
        checked: false,
      },
    }
  },
  methods: {
    addFn() {
      if (this.goods.name.trim() === '' || this.goods.price.length === 0)
        return alert('请输入正确数据')
      if (this.goods.num < 1) {
        this.goods.num = 1
        return alert('商品数量不得少于一个')
      }
      this.goodList.push(this.goods)
    },
  },
}
</script>

<style></style>
